package com.hdoit.apollo.logical.purchase.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hdoit.apollo.logical.cargo.model.Collocation;
import com.hdoit.apollo.logical.cargo.service.ICollocationService;
import com.hdoit.apollo.logical.common.enums.purchase.AllocationState;
import com.hdoit.apollo.logical.common.enums.stock.InStockType;
import com.hdoit.apollo.logical.inStock.model.InStock;
import com.hdoit.apollo.logical.inStock.service.IInStockService;
import com.hdoit.apollo.logical.purchase.dao.IPurchaseDao;
import com.hdoit.apollo.logical.purchase.model.Purchase;
import com.hdoit.apollo.logical.purchase.model.PurchaseCollocation;
import com.hdoit.apollo.logical.purchase.model.PurchaseRecord;
import com.hdoit.apollo.logical.purchase.service.IPurchaseCollocationService;
import com.hdoit.apollo.logical.purchase.service.IPurchaseRecordService;
import com.hdoit.apollo.logical.purchase.service.IPurchaseService;
import com.hdoit.apollo.logical.shop.model.SupplyCargo;
import com.hdoit.apollo.logical.shop.service.ISupplyCargoService;
import com.hdoit.apollo.logical.stock.model.Stock;
import com.hdoit.apollo.logical.stock.model.StockCollocation;
import com.hdoit.apollo.logical.stock.service.IStockCollocationService;
import com.hdoit.apollo.logical.stock.service.IStockService;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.data.dao.base.impl.SuperService;
import com.tennetcn.data.enums.ModelStatus;

/**
 * @author      humaoshu
 * @email       
 * @createtime  2018年05月23日 09:50:23
 * @comment
 */
@Component
public class PurchaseServiceImpl extends SuperService<Purchase> implements IPurchaseService{

	@Autowired
	private IPurchaseCollocationService purchaseCollocationService;
	
	@Autowired
	private IPurchaseDao purchaseDao;
	
	@Autowired
	private ICollocationService collocationService;
	
	@Autowired
	private IStockService stockService;
	
	@Autowired
	private IStockCollocationService stockCollocationService;
	
	@Autowired
	private IInStockService inStockService;
	
	@Autowired
	private IPurchaseRecordService purchaseRecordService;
	
	@Autowired
	private ISupplyCargoService supplyCargoService;
	
	@Override
	public boolean applyPurchaseForPC(Purchase purchase) {
		if (applyChange(purchase)) {
			if (ModelStatus.add.equals(purchase.getModelStatus())) {
				return savePurchaseCollocationForPc(purchase);
			} else {
				
				if (purchaseCollocationService.deletePurchaseCollocations(purchase.getPurchaseId())) {
					return savePurchaseCollocationForPc(purchase);
				}
			}
		}
		return false;
	}
	private boolean savePurchaseCollocationForPc(Purchase purchase) {
		if(StringUtils.isEmpty(purchase.getCollocationIds())||StringUtils.isEmpty(purchase.getPurchaseNums())){
			return true;
		}
		
		if((!StringUtils.isEmpty(purchase.getCollocationIds()))&&!StringUtils.isEmpty(purchase.getPurchaseNums())){
			
			String[] collocationIds = purchase.getCollocationIds().split(",");
			String[] purchaseNums=purchase.getPurchaseNums().split(",");
			String[] purchasePrices=purchase.getPurchasePrices().split(",");
			String[] units=purchase.getUnit().split(",");

			List<PurchaseCollocation> purchaseCollocations=new ArrayList<PurchaseCollocation>();
			PurchaseCollocation purchaseCollocation = null;
			for (int i = 0; i < collocationIds.length; i++) {
				
				Collocation collocation=collocationService.queryModelByCargo(collocationIds[i]);
				
				
				purchaseCollocation = new PurchaseCollocation();
				purchaseCollocation.setId(CommonUtils.getKeyId());
				purchaseCollocation.setPurchaseId(purchase.getPurchaseId());
				purchaseCollocation.setCollocationId(collocationIds[i]);
				purchaseCollocation.setCargoId(collocation.getCargoId());
				purchaseCollocation.setPurchaseNumber(Double.parseDouble(purchaseNums[i]));
				purchaseCollocation.setAllotmentNum(purchaseCollocation.getPurchaseNumber());
				purchaseCollocation.setPurchasePrice(Double.parseDouble(purchasePrices[i]));
				purchaseCollocation.setShopId(purchase.getShopId());
				purchaseCollocation.setCreateDate(DateUtils.getCurrent());
				purchaseCollocation.setDeleteMark(YesOrNoInteger.no);
				purchaseCollocation.setInStockNum(0.0);
				purchaseCollocation.setSurplusNum(0.0);
				purchaseCollocation.setUnit(units[i]);
				
				//存入单位换算比率，方便库存操作
				if (units[i].equals(collocation.getCargo().getUnit())) {
					purchaseCollocation.setRatio(1.0);
				}else if (units[i].equals(collocation.getCargo().getViceFirstUnit())) {
					purchaseCollocation.setRatio(collocation.getCargo().getFirstRatio());
				}else if (units[i].equals(collocation.getCargo().getViceSecondUnit())) {
					purchaseCollocation.setRatio(collocation.getCargo().getSecondRatio());
				}
				//
				
				purchaseCollocation.setCargoNo(collocation.getCargo().getCargoNo());
				purchaseCollocation.setCargoName(collocation.getCargo().getCargoName());
				purchaseCollocation.setCollocationNo(collocation.getCollocationNo());
				purchaseCollocation.setPropertyNameOne(collocation.getPropertyNameOne());
				purchaseCollocation.setPropertyNameTwo(collocation.getPropertyNameTwo());	
				purchaseCollocation.setCollocationState(AllocationState.stayAllocation);
				purchaseCollocation.setModelStatus(ModelStatus.add);
				
				if(!StringUtils.isEmpty(purchase.getSupplierId())){
					SupplyCargo supplyCargo=supplyCargoService.checkSupplyCargo(purchase.getSupplierId(),purchaseCollocation.getCargoId(),purchaseCollocation.getCollocationId());
					if(supplyCargo!=null) {
						supplyCargo.setModelStatus(ModelStatus.update);
						if (units[i].equals(collocation.getCargo().getUnit())) {
							supplyCargo.setSupplyPrice(Double.parseDouble(purchasePrices[i]));
						}else if (units[i].equals(collocation.getCargo().getViceFirstUnit())) {
							supplyCargo.setSupplyPrice(Double.parseDouble(purchasePrices[i])/collocation.getCargo().getFirstRatio());
						}else if (units[i].equals(collocation.getCargo().getViceSecondUnit())) {
							supplyCargo.setSupplyPrice(Double.parseDouble(purchasePrices[i])/collocation.getCargo().getSecondRatio());
						}
					}else {
						supplyCargo=new SupplyCargo();
						supplyCargo.setId(CommonUtils.getKeyId());
						supplyCargo.setSupplierId(purchase.getSupplierId());
						supplyCargo.setCollocationId(collocationIds[i]);
						supplyCargo.setCargoId(collocation.getCargoId());
						if (units[i].equals(collocation.getCargo().getUnit())) {
							supplyCargo.setSupplyPrice(Double.parseDouble(purchasePrices[i]));
						}else if (units[i].equals(collocation.getCargo().getViceFirstUnit())) {
							supplyCargo.setSupplyPrice(Double.parseDouble(purchasePrices[i])/collocation.getCargo().getFirstRatio());
						}else if (units[i].equals(collocation.getCargo().getViceSecondUnit())) {
							supplyCargo.setSupplyPrice(Double.parseDouble(purchasePrices[i])/collocation.getCargo().getSecondRatio());
						}
						
						supplyCargo.setShopId(purchase.getShopId());
						supplyCargo.setCreateDate(DateUtils.getCurrent());
						supplyCargo.setCreateUserId(purchase.getCreateUserId());
						supplyCargo.setCreateUserName(purchase.getCreateUserName());
						supplyCargo.setDeleteMark(YesOrNoInteger.no);
						supplyCargo.setModelStatus(ModelStatus.add);
					}
					supplyCargoService.applyChange(supplyCargo);
				}
				
				purchaseCollocations.add(purchaseCollocation);
			}
			
			if(purchaseCollocations != null && purchaseCollocations.size()>0){
				return purchaseCollocationService.applyChanges(purchaseCollocations);
			}else{
				return true;
			}
		}
		
		return true;
	}
	
	
	@Override
	public Purchase queryModelByKey(String key) {
		
		return purchaseDao.queryModelByKey(key);
	}
	@Override
	public boolean closePurchase(Purchase purchase, String loginId, String loginName) {
		purchase.setModifyDate(DateUtils.getCurrent());
		purchase.setModifyUserId(loginId);
		purchase.setModifyUserName(loginName);
		purchase.setModelStatus(ModelStatus.update);
		for(PurchaseCollocation purchaseCollocation:purchase.getPurchaseCollocations()) {
			
			if(purchaseCollocation.getInStockNum()!=0) {
				Collocation collocation=collocationService.queryModelByCargo(purchaseCollocation.getCollocationId());
				Stock stock=stockService.queryModelByKey(purchaseCollocation.getCargoId());
				Double returnNum=0.0;
				if (purchaseCollocation.getUnit().equals(collocation.getCargo().getUnit())) {
					returnNum=purchaseCollocation.getInStockNum();
				}else if (purchaseCollocation.getUnit().equals(collocation.getCargo().getViceFirstUnit())) {
					returnNum=purchaseCollocation.getInStockNum()*collocation.getCargo().getFirstRatio();
				}else if (purchaseCollocation.getUnit().equals(collocation.getCargo().getViceSecondUnit())) {
					returnNum=purchaseCollocation.getInStockNum()*collocation.getCargo().getSecondRatio();
				}
				stock.setModelStatus(ModelStatus.update);
				for(StockCollocation stockCollocation:stock.getStockCollocations()) {
					if(stockCollocation.getCollocationId().equals(purchaseCollocation.getCollocationId())) {
						stockCollocation.setCollocationNum(stockCollocation.getCollocationNum()-returnNum);
						stockCollocation.setModelStatus(ModelStatus.update);
						stockCollocationService.applyChange(stockCollocation);
						
					}
					
				}
				stock.setStockNum(stock.getStockNum()-returnNum);
				stockService.applyChange(stock);
			}
		}
		List<InStock> inStocks=inStockService.queryInStockHistoryListByKey(purchase.getPurchaseId());
		if(inStocks != null && inStocks.size() !=0 ){
			for(InStock inStock:inStocks) {
				inStock.setType(InStockType.close);
				inStock.setModifyDate(DateUtils.getCurrent());
				inStock.setModifyUserId(loginId);
				inStock.setModifyUserName(loginName);
				inStock.setModelStatus(ModelStatus.update);
			}
			inStockService.applyChanges(inStocks);
		}

		return super.applyChange(purchase);
	}
	
	private boolean savePurchaseRecord(Purchase purchase) {
		PurchaseRecord purchaseRecord=new PurchaseRecord();
		purchaseRecord.setId(CommonUtils.getKeyId());
		purchaseRecord.setPurchaseId(purchase.getPurchaseId());
		purchaseRecord.setPurchaseNum(purchase.getPurchaseNum());
		purchaseRecord.setPurchaseMoney(purchase.getPurchaseMoney());
		purchaseRecord.setType(purchase.getPurchaseState());
		purchaseRecord.setShopId(purchase.getShopId());
		purchaseRecord.setCreateDate(DateUtils.getCurrent());
		purchaseRecord.setCreateUserId(purchase.getCreateUserId());
		purchaseRecord.setCreateUserName(purchase.getCreateUserName());
		purchaseRecord.setDeleteMark(YesOrNoInteger.no);
		purchaseRecord.setModelStatus(ModelStatus.add);
		return purchaseRecordService.applyChange(purchaseRecord);
	}
	
	@Override
	public boolean applyPurchase(Purchase purchase) {
		boolean result=false;
		result=super.applyChange(purchase);
		if(result) {
			result=savePurchaseRecord(purchase);
		}
		return result;
	}
}